package sistem.management.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sistem.manangement.model.SMUser;
import sistem.manangement.model.UserType;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class SalveazaDoctor extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		SMUser mDoctor = new SMUser();
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

		mDoctor.setFirstName(req.getParameter("prenume"));
		mDoctor.setLastName(req.getParameter("nume"));
		mDoctor.setEmail(req.getParameter("email"));
		mDoctor.setType(UserType.MEDIC);

		Key doctorKey = KeyFactory.createKey("user", mDoctor.getEmail());
		Entity doctor = null;
		try {
			doctor = datastore.get(doctorKey);
			System.out.println("adresa de email deja folosita");
			req.setAttribute("status", "fail");
			resp.setContentType("text");
			resp.getWriter().write("fail");
		} catch (EntityNotFoundException e) {
			e.printStackTrace();
			System.out.println("Se creaza un cont de secretara");
			doctor = new Entity(doctorKey);
			doctor.setProperty("nume", mDoctor.getLastName());
			doctor.setProperty("prenume", mDoctor.getFirstName());
			doctor.setProperty("email", mDoctor.getEmail());
			doctor.setProperty("usertype", mDoctor.getType().toString());

			datastore.put(doctor);
			System.out.println("Cont creat cu succes");
			resp.getWriter().write("succes");
		}
	}

}
